const Koa = require("koa");
const app = new Koa();

const Router = require("@koa/router");
const router = new Router();

const path = require("path");
const authRouter = require("./routers/authRouter");
const systemRouter = require("./routers/systemRouter");
const uploadRouter = require("./routers/uploadRouter");
const userRouter = require("./routers/userRouter");
const categoryRouter = require("./routers/categoryRouter");
const postRouter = require("./routers/postRouter");
const tagRouter = require("./routers/tagRouter");
const commitRouter = require("./routers/commitRouter");

const bodyParser = require("koa-bodyparser");
const staticServer = require("koa-static");
const session = require("koa-session");
const render = require("koa-ejs");
const logger = require("koa-logger");

const { sessionConfig, ejsConfig } = require("./config/middlewaresConfig");
const { port } = require("./config/defaultConfig");
const { sequelize } = require("./database/sequlize");
const jwtMiddleware = require("./middleware/jwtMiddleware");
const myFiglet = require("./utils/figlet");

// 静态资源服务器，存储在Public目录下
app.use(staticServer(path.resolve("public")));

// 记录请求日志
app.use(logger());

// 使用session
app.use(session(sessionConfig, app));

// 设置签名的密钥
app.keys = ["your-secret-key"];

// 配置模版引擎
render(app, ejsConfig);

// 使用ctx.body解析中间件
app.use(bodyParser());

// 使用 jwt 校验路由权限
app.use(jwtMiddleware);

// 添加路由请求
app.use(authRouter.routes());
app.use(userRouter.routes());
app.use(systemRouter.routes());
app.use(uploadRouter.routes());
app.use(categoryRouter.routes());
app.use(postRouter.routes());
app.use(tagRouter.routes());
app.use(commitRouter.routes());
// 全局定义方法，用来处理客户端发送的一些 HTTP 请求方法可能并不被服务器所允许的情况
app.use(router.allowedMethods());

app
  .listen(port, () => {
    myFiglet("N o d e");
  })
  .on("error", (err) => {
    console.error("Error occurred while starting the server:", err);
  });

sequelize
  .sync()
  .then(() => {
    myFiglet("S e q u e l i z e");
  })
  .catch((err) => console.log("sequelize", err));
